package com.xingkeduo.configuration.druid;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = {"com.xingkeduo.dao"}, sqlSessionFactoryRef = "sqlSessionFactoryMain")
public class DruidMainDbAConfig {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(DruidMainDbAConfig.class);
	
	@Autowired
    @Qualifier("mainDb")
    private DataSource mainDb;

    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactoryMain() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(mainDb);
        try {  
            //指定mapper xml目录  
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

            factoryBean.setMapperLocations(resolver.getResources("classpath*:mappers/*.xml"));
            return factoryBean.getObject();  
        } catch (Exception e) {  
            logger.error(e.getMessage(), e);  
            throw new RuntimeException(e);  
        } 
    }

    @Bean("sqlSessionTemplateMain")
    @Primary
    public SqlSessionTemplate sqlSessionTemplateMain() throws Exception {
    	// 使用上面配置的Factory
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactoryMain()); 
        return template;
    }
}

